package com.example.user.adapter.in.web.config;

import com.example.user.service.domain.User;
import com.example.user.service.domain.port.GetUserByNamePort;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Collections;

@Configuration
@EnableWebSecurity
@Slf4j
public class SecurityConfig {
    @Resource
    private GetUserByNamePort getUserByNamePort;
    @Bean
    public UserDetailsService userDetailsService() {
        return new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
                log.debug("Loading user by username: {}", username);
                User user = User.getUserByName(username,getUserByNamePort);
                if (user == null) {
                    log.warn("User not found: {}", username);
                    throw new UsernameNotFoundException("用户不存在: " + username);
                }
                return org.springframework.security.core.userdetails.User.builder()
                        .username(user.getName().username())
                        .password(user.getPassword().encryptedValue())
                        .accountExpired(false)
                        .accountLocked(false)
                        .credentialsExpired(false)
                        .build();
            }
        };
    }
}
